local json = require("cjson.safe")
local ngx = ngx
local get_var = require("resty.ngxvar").fetch
local ngx_re = require "ngx.re"

local _M = {}
local mt = { __index = _M }



function _M.string_replace(s, pattern, replace, times)
    local ret = nil
    while times >= 0 do
        times = times - 1
        local s_start, s_stop = string.find(s, pattern, 1, true) -- 1,true means plain searches from index 1
        if s_start ~= nil and s_stop ~= nil then
            s = string.sub(s, 1, s_start - 1) .. replace .. string.sub(s, s_stop + 1)
        end
    end
    return s
end

function _M.existed(list, value)
    for idx, item in ipairs(list) do
        if item == value then
            return true
        end
    end
    return false
end

function _M.ngx_ctx_dump()
    local dump_str = json.encode(ngx.ctx)
    get_var["ae_ctx_dump"] = dump_str
end

function _M.ngx_ctx_load()

    if get_var["ae_ctx_dump"] == nil then
        return
    end

    local dump_str = get_var["ae_ctx_dump"]
    if dump_str ~= '' then
        ngx.ctx = json.decode(dump_str)
    end
end

function _M.get_request_args()
    local args = ngx.req.get_uri_args()
    local post_args, err = nil

    ngx.req.read_body()
    post_args, err = ngx.req.get_post_args()
    if post_args == nil then
        return args
    end

    for k, v in pairs(post_args) do
        args[k] = v
    end

    return args
end

function _M.get_request_args()
    local args = ngx.req.get_uri_args()
    local post_args, err = nil

    ngx.req.read_body()
    post_args, err = ngx.req.get_post_args()
    if post_args == nil then
        return args
    end

    for k, v in pairs(post_args) do
        args[k] = v
    end

    return args
end

-- 扩展string split函数
function string:split(sep)
    local sep, fields = sep or ":", {}
    local pattern = string.format("([^%s]+)", sep)
    self:gsub(pattern, function(c) fields[#fields + 1] = c end)
    return fields
end

-- 获取真实ip
--function _M.get_client_ip(args)
--    local header_table = ngx.req.get_headers();
--
--    -- -H "x-connecting-ip: 1.1.1.1"
--    --for k,v in pairs(header_table) do
--    --    if type(v) == "table" then
--    --        ngx.log(ngx.WARN,"###",k , ": ",table.concat(v,","))
--    --    else
--    --        ngx.log(ngx.WARN,"###",k , ": ",v)
--    --        ngx.log(ngx.WARN,"### var ",ngx.var.http_x_connecting_ip)
--    --    end
--    --
--    --end
--    --ngx.log(ngx.ERR,table.concat(self.args))
--    --for i = 1, #(args) do
--    for _,arg in ipairs(args) do
--        --ngx.log(ngx.WARN,"---",args[i],header_table[args[i]]~=nil)
--        if arg == "remote_addr" then
--            if vars.remote_addr ~= nil then
--                --ngx.log(ngx.WARN,"remote --- ",ngx.var.remote_addr)
--                return vars.remote_addr
--            end
--        elseif header_table[arg] ~= nil then
--
--
--            local ip = header_table[arg]:split(',')[1];
--            --ngx.log(ngx.WARN,"---",ip)
--            if ip ~= nil and ip ~= "-" then
--                return ip;
--            end
--        end
--    end
--    return nil;
--end

-- 压缩字符，去除无用空格，用于redis命令网络传输
function _M.compress_script(s)
    s = ngx.re.gsub(s, [[^\s+]], "", "mjo")
    s = ngx.re.gsub(s, [[,\s+]], ",", "mjo")
    return s
end

function _M.get_client_ip(args)
    --ngx.log(ngx.ERR,"2222"..table.concat(self))
    --local header_table = ngx.req.get_headers();

    -- -H "x-connecting-ip: 1.1.1.1"
    --for k,v in pairs(header_table) do
    --    if type(v) == "table" then
    --        ngx.log(ngx.WARN,"###",k , ": ",table.concat(v,","))
    --    else
    --        ngx.log(ngx.WARN,"###",k , ": ",v)
    --        ngx.log(ngx.WARN,"### var ",ngx.var.http_x_connecting_ip)
    --    end
    --
    --end
    --ngx.log(ngx.ERR,table.concat(self.args))
    --for i = 1, #(args) do
    --ngx.log(ngx.ERR,table.concat(self.get_ip_mode))
    --for _,arg in ipairs(args) do
    --    --ngx.log(ngx.WARN,"---",args[i],header_table[args[i]]~=nil)
    --    if arg == "remote_addr" then
    --        if get_var("remote_addr") ~= nil then
    --            --ngx.log(ngx.WARN,"remote --- ",ngx.var.remote_addr)
    --            return get_var("remote_addr")
    --        end
    --    --elseif header_table[arg] ~= nil then
    --    else
    --
    --
    --        --local ip = ngx_re.split(header_table[arg],",")[1];
    --        local ip = get_var("http_"..arg);
    --        --ngx.log(ngx.WARN,"---",ip)
    --        if ip ~= nil and ip ~= "-" then
    --            return ip;
    --        end
    --    end
    --end
    for _,arg in ipairs(args) do
        local ip = get_var(arg);
        if ip ~= nil and ip ~= "-" then
            return ip;
        end
    end
    return nil;
end



return _M
